package com.mao.mail;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 生成邮件工具类
 * Created by 毛宇鹏 on 16/7/12.
 */
public class BuildMailUtil {

    private String host;
    private String account;
    private String password;
    private String port;
    private final String charset = "UTF-8";
    private static Map<String, BuildMailUtil> instances = new HashMap<String, BuildMailUtil>();

    public BuildMailUtil(){}

    private BuildMailUtil(String port,String account,String password,String host){
        this.host = host;
        this.account = account;
        this.password = password;
        this.port = port;
    }


    public static BuildMailUtil getInstance(String port,String account,String password,String host) {
        if (!instances.containsKey(account)) {
            instances.put(account, new BuildMailUtil(port, account, password,host));
        }
        return instances.get(account);
    }

    private Session getSession(final String address) {
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host); // 新浪smtp服务 "smtp.sina.cn"
        properties.setProperty("mail.smtp.auth","true");
        if ("465".equalsIgnoreCase(port)) {
            properties.put("mail.smtp.socketFactory.port", "465");
            properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.port", "465");
        } else {
            properties.put("mail.smtp.port", port);
        }

        return Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(address,password);
                }
        });
    }

    private InternetAddress parseInternetAddress(String address) throws AddressException, UnsupportedEncodingException {
        InternetAddress actual;
        if ((address.contains("<")) && (address.contains(">"))) {
            String email = address.substring(address.indexOf("<") + 1, address.indexOf(">"));
            String personal = address.substring(0, address.indexOf("<"));
            actual = new InternetAddress(email, personal, charset);
        } else {
            actual = new InternetAddress(address);
        }
        return actual;
    }



    // 测试发送普通文本邮件
//    public void send(String to) {
//        this.floorSendContext(new EmailModel(to));
//    }

    public void send(EmailModel model) {
        this.floorSendContext(model);
    }

    // 发送文本邮件底层实现方法
    private void floorSendContext(EmailModel model) {
        try{

            final InternetAddress sender = parseInternetAddress(account);

            // 创建MinmeMessage对象
            MimeMessage message = new MimeMessage(getSession(sender.getAddress()));
            message.setSentDate(new Date());

            // 设置发件人
            message.setFrom(sender);


            String[] mailToArrays = model.getMailTo().split(";");
            InternetAddress[] toAddress = new InternetAddress[mailToArrays.length];
            for (int i = 0;i<mailToArrays.length;i++) {
                toAddress[i] = parseInternetAddress(mailToArrays[i]);
            }

            // 设置收件人(多个或单个)
            message.addRecipients(Message.RecipientType.TO,toAddress);

            // 设置邮件标题
            message.setSubject(model.getSubjectTitle(),charset);

            // 设置邮件正文
            message.setText(model.getSubjectContxt(),charset);

            // 发送
            Transport.send(message);
            System.out.println("发送邮件成功....");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
